/**
 * 通用 TS 方法封装处理
 * Copyright (c) 2019 ruoyi
 */

// 日期格式化
export function parseTime(time?: string | number | Date, pattern?: string): string | null {
  if (!time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date: Date
  if (time instanceof Date) {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time
        .replace(/-/g, '/')
        .replace('T', ' ')
        .replace(/\.[\d]{3}/g, '')
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }

  const formatObj: Record<string, number> = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }

  return format.replace(/{(y|m|d|h|i|s|a)+}/g, (_, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['日', '一', '二', '三', '四', '五', '六'][value]
    if (_?.length > 0 && value < 10) value = Number('0' + value)
    return value?.toString() || '0'
  })
}

// 表单重置
export function resetForm(ref: { resetFields?: () => void } | null | undefined): void {
  ref?.resetFields?.()
}

// 添加日期范围
export function addDateRange(params: any, dateRange: any[], propName?: string) {
  const search = { ...params }
  search.params =
    typeof search.params === 'object' && search.params !== null && !Array.isArray(search.params)
      ? search.params
      : {}
  dateRange = Array.isArray(dateRange) ? dateRange : []
  if (!propName) {
    search.params['beginTime'] = dateRange[0]
    search.params['endTime'] = dateRange[1]
  } else {
    search.params['begin' + propName] = dateRange[0]
    search.params['end' + propName] = dateRange[1]
  }
  return search
}

// 回显数据字典
interface DictItem {
  label: string
  value: string | number
}
export function selectDictLabel(datas: DictItem[], value: string | number | undefined): string {
  if (value === undefined) return ''
  const actions: string[] = []
  datas.some((item) => {
    if (item.value == String(value)) {
      actions.push(item.label)
      return true
    }
  })
  if (!actions.length) actions.push(String(value))
  return actions.join('')
}

// 回显数据字典（字符串、数组）
export function selectDictLabels(
  datas: DictItem[],
  value: string | number | (string | number)[],
  separator?: string,
): string {
  if (value === undefined || (Array.isArray(value) && value.length === 0)) return ''
  const valStr = Array.isArray(value) ? value.join(',') : String(value)
  const currentSeparator = separator ?? ','
  const temp = valStr.split(currentSeparator)
  const actions: string[] = []

  temp.forEach((v) => {
    const match = datas.some((item) => {
      if (item.value == v) {
        actions.push(item.label + currentSeparator)
        return true
      }
      return false
    })
    if (!match) actions.push(v + currentSeparator)
  })

  return actions.join('').slice(0, -1)
}

// 字符串格式化(%s)
export function sprintf(str: string, ...args: never[]): string {
  let i = 0
  return str.replace(/%s/g, () => {
    const arg = args[i++]
    return arg === undefined ? '' : arg
  })
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str: never): string {
  if (!str || str === 'undefined' || str === 'null') return ''
  return String(str)
}

// 数据合并
export function mergeRecursive(source: any, target: any) {
  for (const p in target) {
    try {
      if (target[p]?.constructor === Object) {
        source[p] = mergeRecursive(source[p] || {}, target[p])
      } else {
        source[p] = target[p]
      }
    } catch {
      source[p] = target[p]
    }
  }
  return source
}

// 构造树型结构数据
export function handleTree(data: any, id = 'id', parentId = 'parentId', children = 'children') {
  const childrenListMap: Record<string, any> = {}
  const tree: any[] = []

  data.forEach((d: any) => {
    const _id = d[id]
    childrenListMap[_id] = d
    if (!d[children]) d[children] = []
  })

  data.forEach((d: any) => {
    const parentObj = childrenListMap[d[parentId]]
    if (!parentObj) {
      tree.push(d)
    } else {
      parentObj[children].push(d)
    }
  })

  return tree
}

// 参数处理
export function tansParams(params: Record<string, any>): string {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    const part = encodeURIComponent(propName) + '='
    if (value !== null && value !== '' && typeof value !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
            const subPart = encodeURIComponent(`${propName}[${key}]`) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}

// 返回项目路径
export function getNormalPath(p: string): string {
  if (!p || p.length === 0 || p === 'undefined') return p
  let res = p.replace('//', '/')
  if (res[res.length - 1] === '/') res = res.slice(0, -1)
  return res
}

// 验证是否为blob格式
export function blobValidate(data: Blob): boolean {
  return data.type !== 'application/json'
}
